import React, { useEffect, useState } from 'react';
import moment from 'moment';
import type { IDateChartsDataType } from '../../type';
import { ToFixed } from '../../tool';
// @ts-ignore
import EchartsComp from './echarts.js';
import styles from './index.less';
// @ts-ignore
import { getCssVariableValue } from '@/utils/utils';

interface IProps {
  /**
   * 图表数据
   */
  data: IDateChartsDataType;
  /**
   * y轴
   */
  xAxisData?: string[];
  /**
   * x轴节点名称
   */
  nodeXName?: string;
  /**
   * x轴节点名称
   */
  nodeYName?: string;
  /**
   *时间
   */
  date?: string;
}

const Charts = (props: IProps) => {
  const { data, date: _date, xAxisData = [], nodeXName = '', nodeYName = '' } = props;
  const date = _date ? moment(_date).format('YYYYMMDD') : '';
  const [nowData, setNowData] = useState<any>();

  // 计算最大值
  const calMax = (arr: any) => {
    const max = Math.max(...arr);
    const maxint = Math.ceil(max / 9.5);
    let maxval = maxint * 10;
    if (maxval == 0 || max < 0) {
      maxval = 0;
    }
    return maxval;
  };

  // 计算最小值
  const calMin = (arr: any) => {
    const min = Math.min(...arr);
    const minint = Math.floor(min / 10);
    const minval = minint * 10;
    return minval;
  };

  // 现货价格&竞价空间相关性tooltip
  const formatNomalTooltip = (val: any[], dateTime?: string) => {
    let str = `<div style='background: #161A1D;min-width:120px;display: inline-block;font-size: 12px; max-height: 400px;overflow-y: auto;'><div style='display: flex;align-items: center;color: #7A7D7F;margin-bottom: 6px'>
  <span>${dateTime}</span>
  <span style='margin-left: 4px'>${val[0].name}</span>
</div>`;
    val.map((item, index) => {
      str += `
        <div style='display: flex;justify-content: space-between;align-items: center;color: #A7A8A9;margin-bottom: ${
          index === val.length - 1 ? '0px' : '6px'
        }'>
          <div style='display: flex;justify-content: flex-start;align-items: center;margin-right:10px'>
            <span style='display:inline-block;width:10px;height:10px;border-radius:5px;background: ${
              item.color
            };margin-right: 4px'></span>
            <span>${item.seriesName}</span>
          </div>
          <span style='color: #A7A8A9; font-weight: 500'>${item.value}</span>
        </div>
      `;
    });
    str += `</div>`;
    return str;
  };

  // 获取options
  const getOption = (_data: IDateChartsDataType, dateTime?: string) => {
    const { nodeX = {}, nodeY = {}, block = {} } = _data || {};
    const _nodeValues = [...(nodeX?.values || []), ...(nodeY?.values || [])];
    const _blockValues = [...(block.values || [])];
    const yNodeMax = calMax(_nodeValues);
    const yNodeMin = calMin(_nodeValues) > 0 ? 0 : calMin(_nodeValues);
    const yBlockMax = calMax(_blockValues);
    const yBlockMin = calMin(_blockValues) > 0 ? 0 : calMin(_blockValues);
    const _option = {
      grid: {
        left: 26,
        top: 30,
        right: 26,
        bottom: 60,
        containLabel: true,
      },
      legend: {
        right: 'center',
        top: 'bottom',
        padding: [0, 0, 32, 0],
        itemGap: 20,
        itemWidth: 15,
        itemHeight: 8,
        textStyle: {
          color: '#D3D4D4',
        },
        data: [
          {
            name: nodeXName,
            // itemStyle: { opacity: 1, borderWidth: 1, borderColor: '#5E92F6', color: '#222629' },
          },
          {
            name: nodeYName,
            // itemStyle: { opacity: 1, borderWidth: 1, borderColor: '#67DCAB', color: '#222629' },
          },
          {
            name: '阻塞价格',
            // itemStyle: { opacity: 1, borderWidth: 1, borderColor: '#E86452', color: '#222629' },
          },
        ],
      },
      tooltip: {
        trigger: 'axis',
        padding: 12,
        show: true,
        formatter: (e: any) => formatNomalTooltip(e, dateTime),
        backgroundColor: '#161A1D',
        borderColor: '#161A1D',
        textStyle: {
          color: '#A7A8A9',
          fontSize: 12,
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: '#A7A8A9',
            width: 1,
            type: 'solid',
          },
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xAxisData,
        axisTick: {
          alignWithLabel: true,
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitNumber: Math.random(),
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          name: '元/MWh',
          position: 'left',
          min: yNodeMin,
          max: yNodeMax,
          splitNumber: 4,
          interval: (yNodeMax - yNodeMin) / 4,
          splitLine: {
            show: true,
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
        },
        {
          type: 'value',
          name: '元/MWh',
          position: 'right',
          min: yBlockMin,
          max: yBlockMax,
          splitNumber: 4,
          interval: (yBlockMax - yBlockMin) / 4,
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-y-line'),
            },
          },
        },
      ],
      series: [
        {
          name: nodeXName,
          type: 'line',
          symbol: 'none',
          data: (nodeX?.values || []).map((item) => ToFixed(item, 2)),
          color: '#5E92F6',
          lineStyle: { width: 1 },
        },
        {
          name: nodeYName,
          type: 'line',
          symbol: 'none',
          data: (nodeY?.values || []).map((item) => ToFixed(item, 2)),
          color: '#67DCAB',
          lineStyle: { width: 1 },
        },
        {
          name: '阻塞价格',
          type: 'line',
          symbol: 'none',
          data: (block?.values || []).map((item) => ToFixed(item, 2)),
          color: '#E86452',
          lineStyle: { width: 1 },
          yAxisIndex: 1,
        },
      ],
    };
    return _option;
  };

  useEffect(() => {
    if (data) {
      const _option = getOption(data, date);
      setNowData(_option);
    }
  }, [data, date]);

  return (
    <div className={styles.container}>{nowData ? <EchartsComp config={nowData} /> : null}</div>
  );
};

export default Charts;
